package com.teamall.web.tssy.controller;

import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonObjectFormatVisitor;
import com.teamall.core.common.BaseController;
import com.teamall.core.common.JModelAndView;
import com.teamall.core.common.Page;
import com.teamall.framework.exception.BaseAppException;
import com.teamall.framework.log.LogManager;
import com.teamall.framework.util.SecurityUtils;
import com.teamall.web.tssy.db.po.TsSyDeptPO;
import com.teamall.web.tssy.db.po.TsSyUserPO;
import com.teamall.web.tssy.service.ITsSyDeptService;
import com.teamall.web.tssy.service.ITsSyUserService;

/**
 * <Description>tssyuser管理 <br>
 * 
 * @author codeCreater <br>
 * @version 1.0<br>
 * @taskId <br>
 * @CreateDate 2014年11月11日 <br>
 * @since V1.0<br>
 * @see com.teamall.web.tssy.controller <br>
 */

@Controller
@RequestMapping("/tssy/tsSyUser")
public class TsSyUserController extends BaseController {

    private static final LogManager logger = LogManager.getLogger(TsSyUserController.class);

    @Autowired
    private ITsSyUserService tsSyUserService;
    @Autowired
    private ITsSyDeptService tsSyDeptService;
    
    @RequestMapping("index")
    public String index(Model model) {
        // ///////
        // TODO 根据业务场景，进行条件分支跳转、设置页面默认值等

        // ///////

        return "/page/tssy";
    }

    @ModelAttribute
    public void initData(Model model)throws BaseAppException {
    	TsSyDeptPO tsdp = new TsSyDeptPO();
    	List<TsSyDeptPO> result = tsSyDeptService.selectByArg(tsdp);
    	Map<String,String> deptMap = new HashMap<>();
    	if(!CollectionUtils.isEmpty(result)){
    		for(TsSyDeptPO dept:result){
    			deptMap.put(dept.getId(), dept.getDeptName());
    		}
    	}
    	model.addAttribute("deptMap", deptMap);
    }
    
    /**
     * 列表查询
     * @param record
     * @param page
     * @param request
     * @return
     * @throws BaseAppException
     */
    @RequestMapping("queryRecordByPage")
    public ModelAndView queryRecordByPage(TsSyUserPO record,
            Page page,HttpServletRequest request) throws BaseAppException {
    	logger.info("queryRecordByPage by record begin...record=[{0}]", record);
    	ModelAndView mv = new JModelAndView("tssy/tsSyUserList",request);
    	//将dwz分页参数转成Page对象
//    	Page page = dwzToPage(dwzPage);
    	Page<TsSyUserPO> resultPage = tsSyUserService.selectByArgAndPage(record, page);
    	mv.addObject("resultPage", resultPage);
    	mv.addObject("record", record);
    	return mv;
    }

    /**
     * 跳转至新增页面
     * @param record
     * @param request
     * @return
     * @throws BaseAppException
     */
    @RequestMapping("initAdd")
    public ModelAndView initAdd(TsSyUserPO record,HttpServletRequest request) throws BaseAppException {
        logger.info("initAdd add begin...record=[{0}]", record);
        ModelAndView mv = new JModelAndView("tssy/tsSyUserAdd", request);
        return mv;
    }
    
    /**
     * 新增用户
     * @param record
     * @return
     * @throws BaseAppException
     */
    @RequestMapping(value="add",method=RequestMethod.POST)
    public ModelAndView add(TsSyUserPO record) throws BaseAppException {
    	try {
    		//新增的时候采用MD5加密初始化密码
			String password = SecurityUtils.MD5("123456");
			record.setPassword(password);
			record.setIsDel("F");
			record.setIsEnable("T");
			Timestamp tt=new Timestamp(new Date().getTime());
			record.setCreateTime(tt);
	        record.setCreateBy(userId);
	        record.setUpdateBy(userId);
	        record.setUpdateTime(tt);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        logger.info("add record begin...record=[{0}]", record);
        tsSyUserService.add(record);
        return ajaxDoneSuccess(this.operSuccess);
    }

    /**
     * 更新用户信息
     * @param record
     * @return
     * @throws BaseAppException
     */
    @RequestMapping(value="update",method=RequestMethod.PUT)
    public ModelAndView update(TsSyUserPO record) throws BaseAppException {
        logger.info("update record begin...record=[{0}]", record);
        record.setLoginName(null);//更新用户的时候不修改登录名
        Timestamp tt=new Timestamp(new Date().getTime());
        record.setUpdateBy(userId);
        record.setUpdateTime(tt);
        tsSyUserService.update(record);
        return ajaxDoneSuccess(this.operSuccess);
    }

    /**
     * 删除用户
     * @param id
     * @return
     * @throws BaseAppException
     */
    @RequestMapping(value = "delete",method=RequestMethod.DELETE)
    public ModelAndView delete(@RequestParam(value = "id",required = true) String id) throws BaseAppException {
        logger.info("delete record begin...id=[{0}]", id);
        tsSyUserService.updateStatus(id);
        return ajaxDoneSuccess(operSuccess);
    }

    /**
     * 查询单个用户
     * @param id
     * @param request
     * @return
     * @throws BaseAppException
     */
    @RequestMapping("qryRecordInfo")
    public ModelAndView qryRecordInfo(@RequestParam(value = "id",
            required = true) String id,HttpServletRequest request) throws BaseAppException {
    	logger.info("qryRecordInfo by id begin...id=[{0}]", id);
    	ModelAndView mv = new JModelAndView("tssy/tsSyUserAdd",request);
    	TsSyUserPO record = tsSyUserService.selectByPrimaryKey(id);
    	mv.addObject("record", record); 
    	return mv;  
    }

    /**
     * 启用用户
     * @param id
     * @return
     * @throws BaseAppException
     */
    @RequestMapping(value = "enable",method=RequestMethod.PUT)
    public ModelAndView enable(@RequestParam(value = "id",required = true) String id) throws BaseAppException {
        logger.info("enable record begin...id=[{0}]", id);
        TsSyUserPO record = tsSyUserService.selectByPrimaryKey(id);
        record.setIsEnable("T");
        Timestamp tt=new Timestamp(new Date().getTime());
        record.setUpdateBy(userId);
        record.setUpdateTime(tt);
        tsSyUserService.update(record);
        return ajaxDoneSuccess(operSuccess);
    }
    
    /**
     * 禁用用户
     * @param id
     * @return
     * @throws BaseAppException
     */
    @RequestMapping(value = "disable",method=RequestMethod.PUT)
    public ModelAndView disable(@RequestParam(value = "id",required = true) String id) throws BaseAppException {
        logger.info("disable record begin...id=[{0}]", id);
        TsSyUserPO record = tsSyUserService.selectByPrimaryKey(id);
        record.setIsEnable("F");
        Timestamp tt=new Timestamp(new Date().getTime());
        record.setUpdateBy(userId);
        record.setUpdateTime(tt);
        tsSyUserService.update(record);
        return ajaxDoneSuccess(operSuccess);
    }
    
    /**
     * 重置密码
     * @param id
     * @return
     * @throws BaseAppException
     */
    @RequestMapping(value = "resetPassword",method=RequestMethod.PUT)
    public ModelAndView resetPassword(@RequestParam(value = "id",required = true) String id) throws BaseAppException {
        logger.info("disable record begin...id=[{0}]", id);
        TsSyUserPO record = tsSyUserService.selectByPrimaryKey(id);
        try {
    		//重置的时候采用MD5加密初始化密码
			String password = SecurityUtils.MD5("123456");
			record.setPassword(password);
			Timestamp tt=new Timestamp(new Date().getTime());
	        record.setUpdateBy(userId);
	        record.setUpdateTime(tt);
		} catch (Exception e) {
			e.printStackTrace();
		}
        tsSyUserService.update(record);
        return ajaxDoneSuccess(operSuccess);
    }
    
    /**
     * 修改密码页面
     * @param record
     * @param request
     * @return
     * @throws BaseAppException
     */
    @RequestMapping("initModifyPassword")
    public ModelAndView initModifyPassword(TsSyUserPO record,HttpServletRequest request) throws BaseAppException {
        logger.info("initModifyPassword begin...record=[{0}]", record);
        ModelAndView mv = new JModelAndView("tssy/tsSyUserModifyPassword", request);
        return mv;
    }
    
    /**
     * 修改密码
     * @param id
     * @param password
     * @return
     * @throws BaseAppException
     */
    @RequestMapping(value = "modifyPassword",method=RequestMethod.POST)
    public ModelAndView modifyPassword(HttpServletRequest request,@RequestParam(value = "password",required = true)String password) throws BaseAppException {
        TsSyUserPO userInfo = (TsSyUserPO)request.getSession().getAttribute(BaseController.LOGIN_SESSION_KEY);
        logger.info("modifyPassword record begin...id=[{0}]", userInfo.getId());
        TsSyUserPO record = tsSyUserService.selectByPrimaryKey(userInfo.getId());
        try {
			record.setPassword(SecurityUtils.MD5(password));
			Timestamp tt=new Timestamp(new Date().getTime());
	        record.setUpdateBy(userId);
	        record.setUpdateTime(tt);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        tsSyUserService.update(record);
        return ajaxDoneSuccess(operSuccess);
    }
    
    @RequestMapping("initModifyInfo")
    public ModelAndView initModifyInfo(TsSyUserPO record,HttpServletRequest request) throws BaseAppException {
        logger.info("initModifyInfo begin...record=[{0}]", record);
        TsSyUserPO userInfo = (TsSyUserPO)request.getSession().getAttribute(BaseController.LOGIN_SESSION_KEY);
        TsSyUserPO po = tsSyUserService.selectByPrimaryKey(userInfo.getId());
        ModelAndView mv = new JModelAndView("tssy/tsSyUserModifyInfo", request);
        mv.addObject("record", po); 
        return mv;
    }
    
    /**
     * 验证是否存在该登录名
     * @param loginName
     * @return
     * @throws BaseAppException
     */
    @RequestMapping(value = "existLoginName",method=RequestMethod.POST)
    @ResponseBody
    public Map existLoginName(@RequestParam(value = "loginName",required = true)String loginName) throws BaseAppException {
    	TsSyUserPO record = new TsSyUserPO();
    	record.addNewConditions("loginName", loginName);
    	List<TsSyUserPO> list = tsSyUserService.selectByArg(record);
    	Map map = new HashMap<>();
        if(!CollectionUtils.isEmpty(list)){
        	map.put("error", "登录名已被占用");
        }else{
        	map.put("ok", "");
        }
        return map;
    }
}
